import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
let bookList = window.sessionStorage.getItem('bookList')
let cartList = window.sessionStorage.getItem('cartList')
let itemList = window.sessionStorage.getItem('itemList')
let store =  new Vuex.Store({
  state: {
    bookList: bookList? JSON.parse(bookList):[],
    cartList: cartList? JSON.parse(cartList):[],
    itemList: itemList? JSON.parse(itemList):[],
  },
  getters: {
  },
  mutations: {
    setBookList(state, data) {
      state.bookList = data;
    },
    addToCart(state,data) {
      // data.isAdd = true  他不行
      Vue.set(data, 'isAdd', true)
      let newData = JSON.parse(JSON.stringify(data))
      newData.checked = false;
      state.cartList.push(newData)
    },
    addItem(state,data) {
      state.itemList.push(data)
      console.log(state.itemList)
    },
    delBookList(state,id) {
      state.cartList.forEach((v,i) => {
        console.log(v.id+'' ===  id+'')
        if(v.id+'' === id+'') {
          state.cartList.splice(i,1)
        }
      })
    }
  },
  actions: {
  },
  modules: {
  }
})
store.subscribe((mutations, state) => {
  if(state.bookList) {
    window.sessionStorage.setItem('bookList', JSON.stringify(state.bookList))
  }
  if(state.cartList) {
    window.sessionStorage.setItem('cartList', JSON.stringify(state.cartList))
  }
  if(state.itemList) {
    window.sessionStorage.setItem('itemList', JSON.stringify(state.itemList))
  }
})
export default store;
